<template>
  <md-nav-bar :title="title" backgroundColor="#eaf8f4" />
  <view class="container">
    <!-- 表单内容 -->
    <view class="form">
      <uni-forms ref="form" :modelValue="data.formData" label-position="top" :rules="data.rules" label-width="100">
        <uni-forms-item label="标题" name="title" required>
          <uni-easyinput type="text" v-model="data.formData.title" placeholder="请输入标题" />
        </uni-forms-item>
        <uni-forms-item label="类型" name="type" required>
          <uni-data-select
            v-model="data.formData.type"
            :localdata="range"
            @change="typeChange"
          ></uni-data-select>
        </uni-forms-item>
        <uni-forms-item label="价格" name="priceYuan" required>
          <uni-easyinput type="number" v-model="data.formData.priceYuan" placeholder="请输入价格" />
        </uni-forms-item>
        <uni-forms-item label="封面" name="imageUrl">
          <template v-slot:label>
            <view class="form-item-label">
              <text class="required-red">*</text>
              <text>封面</text>
            </view>
          </template>
          <uni-file-picker
            v-model="data.formData.imageUrl"
            return-type="object"
            file-mediatype="image"
            :image-styles="{ height: '460rpx', width: '100%' }"
            @select="(e: any) => handleUpload(e, 'imageUrl')">
            <view class="upload-box">
              <text class="plus">+</text>
            </view>
          </uni-file-picker>
        </uni-forms-item>
        
        <uni-forms-item v-if="data.formData.type !== 1" label="音频" name="musicUrl" required>
          <template v-slot:label>
            <view class="form-item-label">
              <text class="required-red">*</text>
              <text>音频</text>
              <text class="red-tip">温馨提示:上传前、请把音频文件上传到微信的“文件传输助手"上，点击导入</text>
            </view>
          </template>
          <uni-file-picker
            v-model="data.formData.musicUrl"
            :sourceType="['album']"
            file-extname="mp3,wav"
            return-type="object"
            file-mediatype="all"
            @select="(e: any) => handleUpload(e, 'musicUrl')">
          </uni-file-picker>
        </uni-forms-item>
        <uni-forms-item label="描述" name="description" required>
          <view class="form-item-textarea">
            <uni-easyinput
                type="textarea"
                :maxlength="500"
                v-model="data.formData.description"
                placeholder="请描述商品" />
          </view>
        </uni-forms-item>  
      </uni-forms>
      <!-- 提交按钮 -->
      <button class="submit-btn" @click="submit">提交</button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

// 接口
import api from '@/api/index';
import type { Music } from '@/api/data';
// 工具 
import { formatUnitYuanToCent, formatUnitCentToYuan } from '@/utils/util';
import { uploadToQiniu } from '@/api/util';
const isEdit = ref(false)
const range = ref([
  { value: 1, text: "诗词" },
  { value: 2, text: "成曲" },
  { value: 3, text: "demo" },
])
const title = ref('添加商品')
const data = reactive({
  formData: {
    title: '',
    type: 1, // 默认诗词 
    price: 0,
    priceYuan: '',
    imageUrl: '',
    description: '',
    musicUrl: '',
    spuId: '',
    skuId: ''
  } as User.Order.Product,
  rules: {
    title: {
      rules: [
        {
          required: true,
          errorMessage: '请输入标题',
        },
      ],
    },
    priceYuan: {
      rules: [
        {
          required: true,
          errorMessage: '请输入价格',
        },
      ],
    },
    imageUrl: {
      rules: [
        {
          required: true,
          errorMessage: '请上传商品图片',
        },
      ],
    },
    musicUrl: {}
  }
});
const form = ref(null);

const handleUpload = async (e: any, key: string) => {
  uni.showLoading({ title: '上传中...', mask: true });
  let { tempFiles } = e;
  const file = tempFiles?.[0];
  // 音频文件只支持mp3和wav格式
  if (key === 'musicUrl' && !['mp3', 'wav'].includes(file?.extname)) {
    uni.showModal({
      title: '提示',
      content: '音频文件只支持mp3和wav格式',
      showCancel: false,
    });
    data.formData[key] = {};
    uni.hideLoading();
    return;
  }
  try {
    const res: any = await uploadToQiniu(file, 'isong/music/' + key);
    if (res) {
      // 格式化组件需要的格式
      const value = {
        url: res.url,
        extname: res?.extname,
        name: res?.name,
      };
      data.formData[key] = value;
    } else {
      data.formData[key] = {};
    }
  } catch (e) {
    data.formData[key] = {};
  }
  uni.hideLoading();
};

const submit = async () => {
  try {
    const res = await form.value?.validate();
    const values = {
      ...res,
      // 处理提交格式
      price: formatUnitYuanToCent(res.priceYuan),
      spuId: data.formData.spuId,
      skuId: data.formData.skuId,
      imageUrl: res?.imageUrl?.url,
      musicUrl: res?.musicUrl?.url
    };
    if(isEdit.value) {
      fetchEditProduct(values)
    } else {
      fetchAddProduct(values);
    }
  } catch (e) {}
};

const typeChange = (val: number) => {
  if(val !== 1) {
    data.rules.musicUrl = {
      rules: [
        {
          required: true,
          errorMessage: '请上传音频文件',
        },
      ],
    }
  } else {
    data.rules.musicUrl = {}
  }
}

/**
 * 接口相关
 */
// 新增提交
const fetchAddProduct = async (params: Music.Create.addProduct) => {
  try {
    await api.Order.addProduct({ ...params });
    uni.showModal({
      title: '提示',
      content: '添加成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/sub/my/myShop'
          });
        }
      },
    });
  } catch (e) {}
};
// 修改提交
const fetchEditProduct = async (params: Music.Create.addProduct) => {
  try {
    await api.Order.productModify({ ...params });
    uni.showModal({
      title: '提示',
      content: '修改成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/sub/my/myShop'
          });
        }
      },
    });
  } catch (e) {}
};
// 获取商品详情
const fetchGetGoodsinfo = async (obj: any) => {
  try {
    const res = await api.Order.productDetail({
      spuId: obj.spuId,
      skuId: obj.skuId
    });
    const _extname = res.data?.imageUrl?.split('.')?.slice(-1)?.[0];
    const _extMusicUrlname = res.data?.musicUrl?.split('.')?.slice(-1)?.[0];
    data.formData = Object.assign(data.formData, res.data, { 
      priceYuan: formatUnitCentToYuan(res.data.price,2),
      spuId: obj.spuId,
      skuId: obj.skuId,
      imageUrl: res.data?.imageUrl ? { url: res.data?.imageUrl, extname: _extname, name: res.data?.title } : undefined,
      musicUrl: res.data?.musicUrl ? { url: res.data?.musicUrl, extname: _extMusicUrlname, name: res.data?.title } : undefined
    });
  } catch (e) {}
};
onLoad(options => {
  // 编辑
  if(options.spuId) {
    isEdit.value = true
    title.value = '编辑商品'
    fetchGetGoodsinfo(options)
  }
})
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #eaf8f4;
  padding-bottom: 60rpx;
  .form {
    margin: 0;
    padding: 0 24rpx;
  }
  .form-group {
    margin-bottom: 32rpx;
  }
  .label {
    font-size: 28rpx;
    color: #222;
    margin-bottom: 12rpx;
    font-weight: 500;
    display: flex;
    align-items: center;
  }
  .required {
    color: #ff4d4f;
    margin-left: 4rpx;
    font-size: 24rpx;
  }
  .input {
    width: 100%;
    height: 80rpx;
    background: #fff;
    border-radius: 16rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    border: none;
    margin-top: 8rpx;
  }
  .textarea {
    width: 100%;
    min-height: 120rpx;
    background: #fff;
    border-radius: 16rpx;
    padding: 16rpx 24rpx;
    font-size: 28rpx;
    border: none;
    margin-top: 8rpx;
  }
  .upload-box {
    width: 100%;
    height: 160rpx;
    background: #fff;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 8rpx;
    font-size: 60rpx;
    color: #bfbfbf;
    border: 2rpx dashed #d9d9d9;
  }
  .plus {
    font-size: 60rpx;
    color: #bfbfbf;
  }
  .disclaimer {
    display: flex;
    align-items: center;
    margin: 24rpx 0 0 0;
    font-size: 24rpx;
    color: #888;
  }
  .submit-btn {
    width: 100%;
    height: 90rpx;
    background: #1fa37a;
    color: #fff;
    font-size: 36rpx;
    border-radius: 60rpx;
    font-weight: 600;
    margin: 40rpx 0 0 0;
    border: none;
    box-shadow: 0 4rpx 16rpx 0 #e0e0e0;
  }
  .submit-btn:disabled {
    background: #b2d8c7;
    color: #fff;
  }
  .tip {
    text-align: center;
    color: #01604a;
    font-size: 26rpx;
    margin-top: 16rpx;
  }
  .form-item-label {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #606266;
    height: 80rpx;
  }
  .red-tip {
    color: #dd524d;;
    font-size: 18rpx;
    margin-left: 10rpx;
  }
  .required-red {
    color: #dd524d;
    font-weight: bold;
  }
  :deep(.form-item-textarea textarea) {
    height: 300px;
  }
}

</style>
